import requests
from lxml import etree
import os

headersvalue = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36 Edg/94.0.992.50'}

def select_catgory():
    print('''网站的壁纸按内容分类，共有 23 种，分别是：\n
    1. 日历    2. 动漫    3. 风景    4. 美女    5. 游戏    6. 影视    7. 动态\n
    8. 唯美    9. 设计    10.花卉    11.动物    12.节日    13.人物    14.美食\n
    15.水果    16.建筑    17.体育    18.军事    19.非主流  20.护眼    21.LOL\n
    22.王者荣耀 23.其他\n\n''')
    choice = int(input('按照分类下载，输入对应分类序号；随机下载，输入“0”。请输入：\n'))
    choices = ['http://www.netbian.com/',
                'http://www.netbian.com/rili/',
                'http://www.netbian.com/dongman/',
                'http://www.netbian.com/fengjing/',
                'http://www.netbian.com/meinv/',
                'http://www.netbian.com/youxi/',
                'http://www.netbian.com/yingshi/',
                'http://www.netbian.com/dongtai/',
                'http://www.netbian.com/weimei/',
                'http://www.netbian.com/sheji/',
                'http://www.netbian.com/huahui/',
                'http://www.netbian.com/dongwu/',
                'http://www.netbian.com/jieri/',
                'http://www.netbian.com/renwu/',
                'http://www.netbian.com/meishi/',
                'http://www.netbian.com/shuiguo/',
                'http://www.netbian.com/jianzhu/',
                'http://www.netbian.com/tiyu/',
                'http://www.netbian.com/junshi/',
                'http://www.netbian.com/feizhuliu/',
                'http://www.netbian.com/s/huyan/',
                'http://www.netbian.com/s/lol/',
                'http://www.netbian.com/s/wangzherongyao/',
                'http://www.netbian.com/qita/']
    global index_urls
    index_urls = []
    index_urls.append(choices[choice])
    global n
    n = int(input("需要下载多少张壁纸？\n"))

def get_pre(n):
    global page_urls
    page_urls = []
    # 网站总共 1216 页
    for i in range(1, n//20+2):
        # 获取每一张图片所在页面的 URL，来下载图片原图
        r_i = requests.get(index_urls[i-1], headers=headersvalue)
        html = etree.HTML(r_i.text)
        page_urls += html.xpath('body//*[@class="list"]/ul//li/a/@href')
        index_url = '{}index_{}.htm'.format(index_urls[0], i+1)
        index_urls.append(index_url)

def get_jpg():
# 获取每一张图片的 URL，下载图片原图
    for page_url in page_urls:
        if page_urls.index(page_url) > n-1:
            break
        r_page = requests.get('http://www.netbian.com'+page_url, headers=headersvalue)
        r_page.encoding = 'GBK'
        html = etree.HTML(r_page.text)
        jpg_main = html.xpath('body//*[@class="pic"]/p/a')
        for i in jpg_main:
            jpg_url = i.xpath('img/@src')[0]
            jpg_title = i.xpath('img/@title')[0]
            jpg = jpg_title, jpg_url
            r_jpg = requests.get(jpg[1], headers=headersvalue)
            r_jpg.encoding = 'GBK'
            if os.path.exists(r'd:\photo_from_52pojie.com'):
                pass
            else:
                os.mkdir(r'd:\photo_from_52pojie.com')
            with open(fr'd:\photo_from_52pojie.com\{jpg[0]}.jpg', 'wb') as f:
                f.write(r_jpg.content)
                print('第{}张图片下载完成！'.format(page_urls.index(page_url)+1))  

def main():
    try:
        select_catgory()
        get_pre(n)

    except ValueError:
        print('输入有误，请输入一个非负整数！')
    except IndexError:
        print('请输入正确的序号！')
    except:
        print('发生未知错误！')
    get_jpg()
    print(f'{n}张图片全部下载完成，默认保存位置是 d:\photo_from_52pojie.com')
main()